package com.ytc.learning.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.ytc.commons.constants.CourseConstants;
import com.ytc.commons.constants.OrdersConstants;
import com.ytc.commons.enums.ErrorCode;
import com.ytc.commons.model.dto.LearningProgressDto;
import com.ytc.commons.model.dto.PageRequest;
import com.ytc.commons.model.dto.RecordDto;
import com.ytc.commons.model.vo.*;
import com.ytc.commons.utils.BeanHelper;
import com.ytc.content.api.ContentClient;
import com.ytc.learning.domain.CourseRecord;
import com.ytc.learning.mappers.CourseRecordMapper;
import com.ytc.learning.service.CourseRecordService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ytc.media.api.MediaClient;
import com.ytc.web.exception.BusinessException;
import com.ytc.web.interceptor.AuthInfoHolder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;

/**
 * <p>
 * 选课记录 服务实现类
 * </p>
 *
 * @author jiuye145
 * @since 2023-04-09
 */
@Service
public class CourseRecordServiceImpl extends ServiceImpl<CourseRecordMapper, CourseRecord> implements CourseRecordService {


    //根据课程发布id，查询用户对此课程的选课数据
    @Override
    public ResponseResult<CourseRecordVo> findRecordByPubId(Long coursePubId) {
        //1.设置查询条件
        LambdaQueryWrapper<CourseRecord> qw = new LambdaQueryWrapper<>();
        qw.eq(CourseRecord::getUserId, AuthInfoHolder.getUserId());
        qw.eq(CourseRecord::getCoursePubId, coursePubId);
        //2.查询
        CourseRecord courseRecord = this.getOne(qw);
        if(courseRecord== null){
            return ResponseResult.okResult();
        }
        //构造返回
        CourseRecordVo courseRecordVo = BeanHelper.copyProperties(courseRecord, CourseRecordVo.class);

        return ResponseResult.okResult(courseRecordVo);
    }

    @Autowired
    private ContentClient contentClient;
    //保存或者更新选课记录
    @Override
    public ResponseResult saveRecord(RecordDto dto) {

        //1.根据用户id 和课程id查询
        LambdaQueryWrapper<CourseRecord> qw = new LambdaQueryWrapper<>();
        qw.eq(CourseRecord::getUserId,dto.getUserId());
        qw.eq(CourseRecord::getCoursePubId,dto.getCoursePubId());
        CourseRecord record = this.getOne(qw);
        //2.如果存在，说明之前有学习的信息
        if(record!=null){
            //2.1修改状态
            record.setPaid(OrdersConstants.PAID);
            //2.2 更新数据表
            this.updateById(record);
        }
        else {
            //数据不存在
            ResponseResult<CoursePubVo> result = contentClient.findById(dto.getCoursePubId());
            CoursePubVo coursePubVo = result.getData();
            record = new CourseRecord();
            record.setUserId(dto.getUserId());
            record.setCoursePubId(dto.getCoursePubId());
            record.setCompanyId(coursePubVo.getCompanyId());
            record.setCourseId(coursePubVo.getCourseId());
            record.setCoursePubName(coursePubVo.getName());
            record.setTeachmode(coursePubVo.getTeachmode());
            record.setStartTime(coursePubVo.getStartTime());
            record.setEndTime(coursePubVo.getEndTime());
            record.setCreateDate(new Date());
            record.setPaid(OrdersConstants.PAID);
        this.save(record);
        }

        return ResponseResult.okResult();
    }

    @Autowired
    private MediaClient mediaClient;

    //查询课程的媒资信息
    @Override
    public ResponseResult<ResourceVo> findPlanUrl(Long coursePubId, Long mediaId, Long teachPlanId) {
        //查询课程，查看课程收费状态
        ResponseResult<CoursePubVo> result = contentClient.findById(coursePubId);
        CoursePubVo data = result.getData();
        String charge = data.getCharge();
        if (charge.equals(CourseConstants.CHARGE_YES)){
            //判断章节是否收费
            ResponseResult<TeachplanVo> result1 = contentClient.findPlanById(teachPlanId);
            TeachplanVo data1 = result1.getData();
            String isPreview = data1.getIsPreview();
            if (isPreview .equals("0")){
                //课程章节收费，未购买
                LambdaQueryWrapper<CourseRecord> wrapper = new LambdaQueryWrapper<>();
                wrapper.eq(CourseRecord::getCoursePubId,coursePubId);
                wrapper.eq(CourseRecord::getUserId,AuthInfoHolder.getUserId());
                CourseRecord record = this.getOne(wrapper);
                if (record == null || record.getPaid().equals(OrdersConstants.NOT_PAID)){
                    throw new BusinessException(ErrorCode.ERROR);
                }
            }
        }
        return mediaClient.findMediaUrl(mediaId);
    }

    //保存学习或者更新进度
    @Override
    public ResponseResult progress(LearningProgressDto dto) {

        //1.根据用户id和课程发布id查询课程
        LambdaQueryWrapper<CourseRecord> qw = new LambdaQueryWrapper<>();
        qw.eq(CourseRecord::getUserId,AuthInfoHolder.getUserId());
        qw.eq(CourseRecord::getCoursePubId,dto.getCoursePubId());
        CourseRecord record = this.getOne(qw);
        //数据存在更新
        if (record != null) {
            record.setTeachplanId(dto.getTeachPlanId());
            record.setTeachplanName(dto.getTeachPlanName());
            this.updateById(record);
        }else {
            //数据不存在，保存设置paid为0
            record= new CourseRecord();
            record.setTeachplanId(dto.getTeachPlanId());
            record.setTeachplanName(dto.getTeachPlanName());
            record.setUserId(AuthInfoHolder.getUserId());
            //查询课程发布信息
            ResponseResult<CoursePubVo> result = contentClient.findById(dto.getCoursePubId());
            CoursePubVo coursePubVo = result.getData();

            record.setCompanyId(coursePubVo.getCompanyId());
            record.setCoursePubId(coursePubVo.getId());
            record.setCourseId(coursePubVo.getCourseId());
            record.setCoursePubName(coursePubVo.getName());
            record.setTeachmode(coursePubVo.getTeachmode());
            record.setStartTime(coursePubVo.getStartTime());
            record.setEndTime(coursePubVo.getEndTime());
            record.setCreateDate(new Date());
            record.setPaid(OrdersConstants.NOT_PAID);
            this.save(record);
        }
              return ResponseResult.okResult();
        }

    @Override
    public ResponseResult MyList (PageRequest request){
        Page<CourseRecord> pageParam=new Page<>(request.getPageNo(),request.getPageSize());
//        //创建查询条件
        LambdaQueryWrapper<CourseRecord> qw=new LambdaQueryWrapper<>();
        //分页查询
        Page<CourseRecord> page=this.page(pageParam,qw);
        return new PageResponseResult(page.getTotal(),page.getRecords());
    }

}

